package com.carrent.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.carrent.sys.constast.SysConstast;
import com.carrent.sys.domain.User;
import com.carrent.sys.service.IUserService;
import com.carrent.sys.utils.WebUtils;
import com.carrent.sys.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
//@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "123456";
    }


    @RequestMapping({"/toLogin","/"})
    public String toLogin(){
        return "system/main/login";
    }

    @PostMapping("/check")
    public String login(UserVo userVo, Model model){
        User user = this.userService.login(userVo);
        if (null != user){
            WebUtils.getHttpSession().setAttribute("user", user);
            // 记录日志
            model.addAttribute("user", user);
            System.out.println(user);
            return "redirect:/index";
        }else{
            model.addAttribute("error", SysConstast.USER_LOGIN_ERROR_MSG);
            return "system/main/login";
        }
    }


    /**
     * 得到登陆验证码
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping("/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,5);
        session.setAttribute("code",lineCaptcha.getCode());
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(lineCaptcha.getImage(),"JPEG",outputStream);
    }


}
